package com.xiaoshuidi.cloud.module.contract.job;

import com.xiaoshuidi.cloud.framework.common.pojo.PageParam;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.tenant.core.job.TenantJob;
import com.xiaoshuidi.cloud.module.contract.dal.dataobject.bill.RentOrderDO;
import com.xiaoshuidi.cloud.module.contract.service.bill.RentOrderService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 催收短信任务
 */
@Component
@TenantJob
@Slf4j
public class OrderReminderSmsJob {
    @Resource
    private RentOrderService rentOrderService;

    @XxlJob("rentOrderReminderJob")
    public void remindSms() {
        log.info("催款账单 - 执行开始");
        PageParam page = new PageParam();
        page.setPageSize(100);
        PageResult<RentOrderDO> pageResult = rentOrderService.getReminderOrder(page);
        if (pageResult.getTotal() == 0) {
            log.info("没有需要催款的账单");
            XxlJobHelper.handleSuccess("没有需要催收的账单");
            return;
        }
        while(CollectionUtils.isNotEmpty(pageResult.getList())) {
            List<RentOrderDO> list = pageResult.getList().stream()
                    // 当天已催款的不再催款
                    .filter(o -> o.getLastRemindTimes() == null || !o.getLastRemindTimes().toLocalDate().isEqual(LocalDate.now()))
                    .filter(o -> StringUtils.isNotBlank(o.getPhone()))
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(list)) {
                rentOrderService.orderReminder(list);
            }
            page.setPageNo(page.getPageNo() + 1);
            pageResult = rentOrderService.getReminderOrder(page);
        }
        XxlJobHelper.handleSuccess("共发送催收短信" + pageResult.getTotal() + "条");
        log.info("催款账单 - 执行结束");
    }

}
